/* This application is developed by Sameera Bandara
 * sole purpose of this class is to handle database access
 */





package com.project.visitAll;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataHandler extends SQLiteOpenHelper {
	 
	  private static final String DBNAME = "visitAll.sqlite";
	  private DataHandler myDBHelper;
	  private SQLiteDatabase myDB;
	  private final Context myContext;
	 
	  public DataHandler(Context context) {
	    super(context, DBNAME, null, 2);
	    this.myContext = context;
	   
	  }
	 
	  @Override
	  public void onCreate(SQLiteDatabase db) {
	  }
	 
	  @Override
	  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	  }
	 
	  public DataHandler open() throws SQLException {
	     myDBHelper = new DataHandler(myContext);
	     myDB = myDBHelper.getWritableDatabase();
	     return this;
	  }
	  Cursor getRaws(String type)
	   {
		  String d="SELECT name, latitude, longitude FROM "+type;
		  Cursor cur=myDB.rawQuery(d,null);
		  return cur;
	   }
	  public void createDatabase() throws IOException {
		  
		    InputStream assetsDB = myContext.getAssets().open("visitAll.sqlite");
		    OutputStream dbOut = new FileOutputStream("/data/data/com.project.visitAll/databases/visitAll.sqlite");
		 
		    byte[] buffer = new byte[1024];
		    int length;
		    while ((length = assetsDB.read(buffer))>0){
		      dbOut.write(buffer, 0, length);
		    }
		 
		    dbOut.flush();
		    dbOut.close();
		    assetsDB.close();
		}

	}